package exttable.timetable.xlsgenerator;

import exttable.timetable.ETestType;
import exttable.timetable.models.AnalysisModel;
import exttable.timetable.models.VisitModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import utils.Localisation;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Apr 30, 2010
 * Time: 9:55:11 AM
 * To change this template use File | Settings | File Templates.
 */
public class XLSGenerator {
    public static final short FONT_HEIGHT = 12;

    public static void createFile(Map<ETestType, List<AnalysisModel>> data) throws IOException {

        FileOutputStream out = null;
        Cell cell;
        Row row;
        try {
            out = new FileOutputStream("C:\\timetable.xls");
            Workbook wb = new HSSFWorkbook();
            Sheet s = wb.createSheet();
            int rowNum = 0;
            int visitNum = 2;
            CellStyle cs = wb.createCellStyle();
            Font f = wb.createFont();

            f.setFontHeightInPoints(FONT_HEIGHT);
            f.setBoldweight(Font.BOLDWEIGHT_BOLD);
            cs.setFont(f);

            for (Map.Entry<ETestType, List<AnalysisModel>> result : data.entrySet()) {
                row = s.createRow(rowNum);
                cell = row.createCell(0);
                cell.setCellStyle(cs);
                cell.setCellValue(result.getKey().name());
                int vis = result.getValue().get(0).getVisitModel().size();
                for (int i = 2; i < vis + 2; i++) {
                    cell = row.createCell(i);
                    cell.setCellValue(Localisation.getMessage("timetable.visit") + (i - 2));
                }

                for (AnalysisModel amResult : result.getValue()) {
                    rowNum++;
                    row = s.createRow(rowNum);
                    for (VisitModel vmResult : amResult.getVisitModel()) {
                        row.createCell(0).setCellValue(amResult.toString());
                        row.createCell(1).setCellValue(amResult.getAnalysis().getAnalysisId());
                        row.createCell(visitNum).setCellValue(vmResult.isCarried() ? "1" : "0");
                        visitNum++;
                    }
                    visitNum = 2;
                }
                rowNum++;
            }
            wb.write(out);
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException("error");
        }
        finally {
            out.close();
        }
    }
}
